package com.atgugu.flink.chapter11.tvf;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2022/4/12 8:59
 */
public class Flink03_TVF_Cumulate {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("sensor_1", 1001L, 1),
                new WaterSensor("sensor_1", 3000L, 3),
                new WaterSensor("sensor_1", 4000L, 4),
                new WaterSensor("sensor_1", 6001L, 6),
                new WaterSensor("sensor_1", 8001L, 8),
                new WaterSensor("sensor_1", 12001L, 12),
                new WaterSensor("sensor_1", 16001L, 16),
                new WaterSensor("sensor_1", 22001L, 22)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts").rowtime(), $("vc"));
        tEnv.createTemporaryView("sensor", table);
        
        // 滑动窗口
        // 窗口长度必须是滑动步长的整数倍
        tEnv
            .sqlQuery("select" +
                          " window_start, " +
                          " window_end, " +
                          " id, " +
                          " sum(vc) vc_sum " +
                          "from table(  " +
                          "     cumulate(table sensor, " +
                          "     descriptor(ts), " +
                          "     interval '2' seconds, " +
                          "     interval '10' seconds)) " +
                          "group by id, window_start, window_end")
            .execute()
            .print();
            
        
        
    }
}
/*

每隔1小时, 计算一下当天的uv
1日
0-1 时 的uv
0-2 时 的uv
0-3 时 的uv
...

0-24 是 的uv

2日
...

窗口的长度的增长有一个定值
窗口的最大长度


 */